/*
 * Program.cpp
 *
 * Created: 11/16/2013 12:18:29 PM
 *  Author: brodzki
 */ 

#include <avr/interrupt.h>

#include "UsartHandler.h"
#include "Config.h"
#include "DisplayHandler.h"
#include "Communication.h"
#include "ThermometerHandler.h"
#include "RelayHandler.h"
#include "CommandDispatcher.h"
#include "EAC.h"

IComm *comm_manager;

ISR(USART_RXC_vect)
{
	comm_manager->handle_input();
}

ISR(USART_TXC_vect)
{
	comm_manager->handle_output();
}

int main()
{
	NullTerminatedComm null_comm_impl;
	DataFrameComm frame_comm_impl;
	comm_manager = &frame_comm_impl;
	
	UsartHandler::initialize();
	sei();	
	DisplayHandler		display(Config::get_display_config());
	RelayHandler		relay(&DDRD, &PORTD, PD7);
	ThermometerHandler	thermometer(&DDRB, &PINB, PB0);
	
	Registers ext;
	ext.ddr  = &DDRD;
	ext.pin  = &PIND;
	ext.port = &PORTD;
	
	EAC line(ext, 6);
	line.enable_pull_up();
	
	CommandDispatcher	dispatcher;
	dispatcher.display	= &display;
	dispatcher.relay	= &relay;
	dispatcher.thermo	= &thermometer;
	
	while(true)
	{
		if(comm_manager->was_data_received())
		{
			dispatcher.dispatch(frame_comm_impl.received_data.command);
		}
		else
		{
			_delay_ms(500);
			display.clear();
			if(line.state())
			{
				display.write_text("opened");
			}
			else
			{
				display.write_text("closed");
			}
		}
	}
}